package com.guiwu.caiguanlin.writeTest;

/**
 * 线程A、B交替打印
 */
public class ReplacePrint {

    private static volatile int i = 1;
    private static final int MAX_LENGTH = 100;
    private static final Object LOCK = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (LOCK) {
                try {
                    while (i < MAX_LENGTH) {
                        if (i % 2 == 0) {
                            LOCK.wait();
                        }
                        System.out.println("A" + i);
                        i++;
                        LOCK.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }, "A").start();

        new Thread(() -> {
            synchronized (LOCK) {
                try {
                    while (i < MAX_LENGTH) {
                        if (i % 2 == 1) {
                            LOCK.wait();
                        }
                        System.out.println("B" + i);
                        i++;
                        LOCK.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();


    }
}
